package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.RecommendQuanzi;
import com.tanhua.domain.mongo.TimeLine;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MomentApiImpl implements MomentApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void add(Publish publish) {
        //设置创建时间
        long timeMillis = System.currentTimeMillis();
        publish.setCreated(timeMillis);
        //生成动态id
        ObjectId objectId = new ObjectId();
        publish.setId(objectId);
        //添加到动态表
        mongoTemplate.insert(publish);
        //创建timeLine
        TimeLine timeLine = new TimeLine();
        timeLine.setCreated(timeMillis);
        timeLine.setPublishId(objectId);
        timeLine.setUserId(publish.getUserId());
        //添加到用户自己的时间表
        mongoTemplate.insert(timeLine, "quanzi_time_line_" + publish.getUserId());
        //添加好友的时间表
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //添加到好友的时间表
        if (!CollectionUtils.isEmpty(friendList)) {
            friendList.forEach(friend -> {
                TimeLine friendTimeLine = new TimeLine();
                friendTimeLine.setUserId(publish.getUserId());
                friendTimeLine.setPublishId(objectId);
                friendTimeLine.setCreated(timeMillis);
                mongoTemplate.insert(friendTimeLine, "quanzi_time_line_" + friend.getFriendId());
            });
        }
    }

    @Override
    public PageResult findByPage(Long longUserId, Long page, Long pageSize) {
        Query query = new Query();
        String collectionName="quanzi_time_line_"+longUserId;
        long total = mongoTemplate.count(query, collectionName);
        List<Publish> publishList = new ArrayList<>();
        if (total>0){
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
            List<TimeLine> timeLines = mongoTemplate.find(query, TimeLine.class, collectionName);
            if (!CollectionUtils.isEmpty(timeLines)){
                List<ObjectId> publishId = timeLines.stream().map(TimeLine::getPublishId).collect(Collectors.toList());
                Query id = new Query(Criteria.where("_id").in(publishId));
                id.with(Sort.by(Sort.Order.desc("created")));
                publishList = mongoTemplate.find(id, Publish.class);
            }
        }
        return PageResult.pageResult(page,pageSize,publishList,total);
    }

    @Override
    public PageResult queryRecommendPublishList(Long longUserId, Long page, Long pagesize) {
        Query query = new Query(Criteria.where("userId").is(longUserId));
        long total = mongoTemplate.count(query, RecommendQuanzi.class);
        List<Publish> publishLists = new ArrayList<>();
        if (total>0){
            query.skip((page-1)*pagesize).limit(pagesize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
            List<RecommendQuanzi> timeLines = mongoTemplate.find(query, RecommendQuanzi.class);
            if (!CollectionUtils.isEmpty(timeLines)){
                List<ObjectId> publishIds = timeLines.stream().map(RecommendQuanzi::getPublishId).collect(Collectors.toList());
                Query publishQuery = new Query(Criteria.where("_id").in(publishIds));
                publishQuery.with(Sort.by(Sort.Order.desc("created")));
                publishLists = mongoTemplate.find(publishQuery, Publish.class);
            }
        }
        return PageResult.pageResult(page,pagesize,publishLists,total);
    }

    @Override
    public PageResult findMyPublishLiset(Long page, Long pagesize, Long userId) {
        Query userID = new Query(Criteria.where("userId").is(userId));
        long total = mongoTemplate.count(userID, Publish.class);
        List<Publish> publishList = new ArrayList<>();
        if (total>0){
            userID.skip((page-1)*pagesize).limit(pagesize.intValue());
            userID.with(Sort.by(Sort.Order.desc("created")));
            publishList = mongoTemplate.find(userID, Publish.class);
        }


        return PageResult.pageResult(page,pagesize,publishList,total);
    }

    @Override
    public Publish findPublishById(String userId) {
        Publish byId = mongoTemplate.findById(userId, Publish.class);
        return byId;
    }
}